package com.wechat.weather.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wechat.weather.config.WechatAccountConfig;
import com.wechat.weather.service.MessageService;
import com.wechat.weather.util.HttpClient;
import com.wechat.weather.util.WxUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author: xiaojiahui@dtxytech.com
 * @since: 2024-12-09  14:53
 * @Description: TODO
 */
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WechatAccountConfig wechatAccountConfig;

    @Override
    public void sendMessage(Integer loveDate) {
        Map<String, Object> userMap = getUserMap();
        Set<String> keySet = userMap.keySet();
        keySet.forEach(userId -> sendWxMessage(userId, userMap.get(userId).toString()));
    }

    private void sendWxMessage(String userId, String city) {
        WxMpTemplateMessage.WxMpTemplateMessageBuilder builder = WxMpTemplateMessage.builder();
        //指定具体的已关注过测试号的用户
        builder.toUser(userId);
        builder.templateId(wechatAccountConfig.getTemplateId());
        WxMpTemplateMessage build = builder.build();
        //封装日期 年 月 日 周
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        LocalDate now = LocalDate.now();
        String dayOfWeek = now.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.CHINA).replace("星期", "周");
        //封装天气信息
        JSONObject jsonObject = getWeather(dayOfWeek, city);
        //获取土味情话
        String loveTalk = getLoveTalk();
        String s1 = "";
        String s2 = "";
        //字数大于20，推送到公众号展示的时候会被截断，因此把长文本内容分为两段
        if (loveTalk.length() > 20) {
            s1 = loveTalk.substring(0, 20);
            s2 = loveTalk.substring(20);
        } else {
            s1 = loveTalk;
        }
        //封装消息模板
        build.addData(new WxMpTemplateData("nowDate", now.format(formatter) + " " + dayOfWeek))
                .addData(new WxMpTemplateData("city", city))
                .addData(new WxMpTemplateData("temperature", jsonObject.getString("temperature")))
                .addData(new WxMpTemplateData("weather", jsonObject.getString("weather")))
                .addData(new WxMpTemplateData("air_quality", jsonObject.getString("air_quality")))
                .addData(new WxMpTemplateData("wind", jsonObject.getString("wind")))
                .addData(new WxMpTemplateData("txt", s1))
                .addData(new WxMpTemplateData("txt1", s2));
        String msg;
        try {
            //发送消息模板
            msg = wxMpService.getTemplateMsgService().sendTemplateMsg(build);
            WxUtil.add();
            log.info("msg:{}", msg);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }

    private Map<String, Object> getUserMap() {
        Map<String, Object> map = new HashMap<>();
        String touser = wechatAccountConfig.getTouser();
        List<String> list = Arrays.asList(touser.split(","));
        list.forEach(str -> {
            //xjh
            if (str.equals("")) {
                map.put(str, "长沙");
            }
        });
        return map;
    }

    //请求土味情话接口
    private String getLoveTalk() {
        String resultString = HttpClient.doGet("https://apis.tianapi.com/saylove/index?key=959e944b86a97c4baf0e4a7762488751");
        JSONObject jsonObject = JSONObject.parseObject(resultString);
        String result = jsonObject.getString("result");
        return JSONObject.parseObject(result).getString("content");
    }

    //请求天气接口，获取天气信息
    private JSONObject getWeather(String dayOfWeek, String city) {
        String resultString = HttpClient.doGet("https://v2.api-m.com/api/weather?city=" + city);
        JSONObject jsonObject = JSONObject.parseObject(resultString);
        JSONArray jsonArray = JSONArray.parseArray(JSONObject.parseObject(jsonObject.get("data").toString()).get("data").toString());
        AtomicReference<JSONObject> result = new AtomicReference<>(new JSONObject());
        jsonArray.forEach(item -> {
            JSONObject json = (JSONObject) item;
            if (json.getString("date").equals(dayOfWeek)) {
                result.set((JSONObject) item);
            }
        });
        return result.get();
    }
}
